#include <dbg.h>

#include <cassert>

using namespace std;

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int maxNum = n * n, curNum = 1;
        int row = 0, column = 0, directionIndex = 0;

        vector<vector<int>> matrix(n, vector<int>(n, 0));
        vector<vector<int>> directions = {
            {0, 1}, {1, 0}, {0, -1}, {-1, 0}};  // 右下左上

        while (curNum <= maxNum) {
            matrix[row][column] = curNum;
            ++curNum;
            int nextRow = row + directions[directionIndex][0],
                nextColumn = column + directions[directionIndex][1];
            if (nextRow < 0 || nextRow >= n || nextColumn < 0 ||
                nextColumn >= n || matrix[nextRow][nextColumn] != 0) {
                directionIndex =
                    (directionIndex + 1) % 4;  // 顺时针旋转至下一个方向
            }
            row = row + directions[directionIndex][0];
            column = column + directions[directionIndex][1];
        }

        return matrix;
    }
};

int main() {
    Solution s;

    int input1 = 3, input2 = 1;
    vector<vector<int>> output1{{1, 2, 3}, {8, 9, 4}, {7, 6, 5}}, output2{{1}};

    assert(s.generateMatrix(input1) == output1);
    dbg("pass 1");
    assert(s.generateMatrix(input2) == output2);
    dbg("pass 2");

    return 0;
}